<?php

namespace Services\Article;

use Common\Model\Article\ArticleModel;
use Common\Util\CmsData;
use Services\BaseService;

class ArticleService extends BaseService
{
    /** @var ArticleModel $articleModel */
    private $articleModel;

    public function __construct()
    {
        $this->articleModel = new ArticleModel();
    }

    public function list()
    {
        $cateId = $this->getParam('cate_id');
        $baseWhere = ['cate_id' => $cateId];
        if ($this->getParam('call_from') == ArticleModel::CALL_FROM_LOOkCARD) {
            $baseWhere['is_yinsi'] = ArticleModel::NOT_YSINSI;
        }
        $pagesize = $this->getParam('page_size');
        $limit = $this->getParam('page_limit');
        $offset = ($pagesize - 1) * $limit;

        if (empty($order)) $order = 'id Desc';
        $baseWhere['is_delete'] = 0;
        $data_list = $this->articleModel->where($baseWhere)->order($order)->limit($offset, $limit)->select();
        foreach ($data_list as $key => $val) {
            $info = M('user_cms_category')->where(['id' => $cateId])->find();
            $cate_info = $info ? $info : [];
            $data_list[$key]['cate_name'] = $cate_info['cate_name'];
        }
        return $data_list ? $data_list : [];
    }

    public function articleInfo($articleId,$fields = '*'){
        $t_cms_article = M('user_cms_article');
        $where['id'] = $articleId;
        $query = $t_cms_article->where($where);
        if($fields != '*'){
            $query = $query->field($fields);
        }
        $data_info = $query->find();
        if(!$data_info){
            return [];
        }
        $data_info['content'] = $data_info['content'] ? json_decode($data_info['content'], true) : [];
        //过滤文章内容
        $data_info['content'] = self::filterArticleContent($data_info['content']);
        $cate_info = CmsData::getCateInfo($data_info['cate_id']);
        $data_info['cate_name'] = arr_get($cate_info,'cate_name','');
        return $data_info;
    }

    private static function filterArticleContent($content = []){
        $newContent = [];
        foreach ($content as $key => $val){
            $_content = arr_get($val, 'content', '');
            if(!$_content){
                continue;
            }
            $newContent [] = $val;
        }
        return $newContent;
    }
}
